package com.fjnu.web;

import com.fjnu.dto.ArticleConditionDto;
import com.fjnu.dto.ArticleDto;
import com.fjnu.dto.ArticleUpdateDto;
import com.fjnu.entity.Article;
import com.fjnu.service.ArticleService;
import com.fjnu.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/blog-api/v0.1")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping("/article/list")
    public ResponseResult list(@RequestBody ArticleConditionDto articleCond) {
        try {
            log.info("查询文章列表 - 条件: {}", articleCond);
            return ResponseResult.success(articleService.queryByArticleCondition(articleCond, 1, 10));
        } catch (Exception e) {
            log.error("查询文章列表失败: {}", e.getMessage());
            return ResponseResult.error("查询文章列表失败");
        }
    }

    @PostMapping("/article/add")
    public ResponseResult add(@RequestBody ArticleDto articleDto) {
        try {
            log.info("新增文章 - 标题: {}", articleDto.getTitle());

            Article article = new Article();
            BeanUtils.copyProperties(articleDto, article);
            article.setCreateTime(new Date());
            article.setUpdateTime(new Date());

            Article result = articleService.insertArticle(article);
            return ResponseResult.success(result, "文章添加成功");
        } catch (Exception e) {
            log.error("新增文章失败: {}", e.getMessage());
            return ResponseResult.error("新增文章失败: " + e.getMessage());
        }
    }

    @PostMapping("/article/update")
    public ResponseResult update(@RequestBody ArticleUpdateDto articleUpdateDto) {
        try {
            log.info("修改文章 - 文章ID: {}", articleUpdateDto.getId());

            int result = articleService.updateArticle(articleUpdateDto);
            if (result > 0) {
                return ResponseResult.success("文章修改成功");
            } else {
                return ResponseResult.error("文章修改失败");
            }
        } catch (Exception e) {
            log.error("修改文章失败: {}", e.getMessage());
            return ResponseResult.error("修改文章失败: " + e.getMessage());
        }
    }

    @GetMapping("/article/{id}/publish")
    public ResponseResult publish(@PathVariable String id) {
        try {
            log.info("发布文章 - 文章ID: {}", id);

            // 这里需要用户ID，简化处理
            String userId = "1";
            int result = articleService.publishArticle(id, userId);
            if (result > 0) {
                return ResponseResult.success("文章发布成功");
            } else {
                return ResponseResult.error("文章发布失败");
            }
        } catch (Exception e) {
            log.error("发布文章失败: {}", e.getMessage());
            return ResponseResult.error("发布文章失败: " + e.getMessage());
        }
    }
}